// 工具类js 
// promise+ajax
export function ajaxTool(url,method,token){
    return new Promise((resolve,reject)=>{
        let xhr = new XMLHttpRequest();
        xhr.open(method,url);
        xhr.setRequestHeader('Content-type','application/json');
        if(token){
            xhr.setRequestHeader('x-token',token);
        };
        if(method === "POST"){
            xhr.send(JSON.stringify(data));
        }else{
            xhr.send();
        };
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    const data = JSON.parse(xhr.responseText);
                    resolve(data);
                }else{
                    reject('请求错误，请检查参数是否正确');
                };
            };
        };
    });
};
// 老师版promise+ajax
function myAjax(url,method,data,token){
    let promise = new Promise((resolve,reject) => {
        let xhr = new XMLHttpRequest()
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if((xhr.status >= 200 && xhr.status < 300)||xhr.status === 304){
                    resolve(JSON.parse( xhr.response))
                }else{
                    reject(new Error("error"))
                }
            }
        }
        if(method.toUpperCase() === "GET"){
           let paramslist = [];
           for(let key in data){
               paramslist.push(key + "=" + data[key])
            }
            // console.log(paramslist);
           //根据get请求方法对url进行拼接
           let params = paramslist.join("&");
           url = url + "?" + params;
         
           xhr.open("get",url);
           //使用get请求将内容连接在url后面
           if(token){
               // xhr.headers.token = token
               xhr.setRequestHeader('x-token',token)
           };
                // 如果是cookie，就设为true;
        //    xhr.withCredentials = true;
           xhr.send();

        };
        if(method.toUpperCase() === "POST"){
            xhr.open("post", url);
            xhr.setRequestHeader("Content-Type", "application/json");
            // xhr.setRequestHeader('x-token',token)
            if(token){
                xhr.setRequestHeader['x-token'] = token;
            };
            xhr.send(JSON.stringify(data));
            //使用post请求时将内容放在send里面
        };

    })
    return promise
};

// 过期Storage
let myStorage = {
    set(key,value,time){
        if(!time){
            time = 60;
        };
        const endTime = +new Date() + time * 60 * 1000;
        localStorage.setItem(key,JSON.stringify({
            data:value,
            time:endTime,
        }));
    },
    get(key){
        if(!localStorage.getItem(key)){
            return null;
        };
        let result = JSON.parse(localStorage.getItem(key));
        let nowTime = +new Date();
        if(nowTime > result.time){
            remove(key);
            return null;
        }else{
            return result.data;
        };
    },
    remove(key){
        localStorage.removeItem(key);
    },
};

// 防抖
export function debounce(fn,wait,immediate){
    if(typeof fn !== 'function'){
        window.alert('输入的不是一个函数');
    };
    if(typeof wait !== 'number'){
        window.alert('输入的不是一个数字');
    };
    if(typeof immediate !== 'boolean'){
        window.alert('输入的不是一个布尔值');
    };
    let timer;
    return function proxy(){
        if(timer){
            clearTimeout(timer);
        };
        if(immediate){
            let timeNow = !timer;
            timer = setTimeout(()=>{
                timer = null;
            },wait);
            if(timeNow){
                fn.apply(this,arguments);
            };
        }else{
            timer = setTimeout(()=>{
                fn.apply(this,arguments);
            },wait);
        };
    };
};

// 节流
export function torottled(fn,delay){
    let timer = null;
    let startTime = Date.now();
    return function proxy(){
        clearTimeout(timer);
        let curTime = Date.now();
        let remaining = delay - (curTime - startTime);
        if(remaining < 0){
            fn();
            startTime = Date.now();
        }else{
            timer = setTimeout(fn,remaining);
        };
    };
};

// 暴露函数
export default{
    myAjax,
    myStorage,
    debounce,
    torottled,
};

